﻿using System;
using System.Windows.Forms;
using desktop.db;
using desktop.Entity;

namespace desktop.Login
{
    public partial class LoginForm : Form
    {
        private LoginHandler _loginHandler;

        public LoginForm(Database db)
        {
            InitializeComponent();

            tipKorisnika.SelectedIndex = 0;

            _loginHandler = new LoginHandler(db);
            Success = false;
        }

        #region Properties
        
        public bool Success 
        { 
            get; 
            private set; 
        }

        public Uposlenik LogiraniUposlenik
        {
            get;
            private set;
        }

        #endregion

        #region GUI Handlers

        private void login_Click(object sender, EventArgs e)
        {
            string tip  = (string)tipKorisnika.SelectedItem;
            string user = username.Text;
            string pw   = password.Text;

            if (user == string.Empty || pw == string.Empty || tip == string.Empty)
            {
                MessageBox.Show("Morate unijeti sve podatke!", "Greska", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!_loginHandler.Login(user, pw, tip))
            {
                _login_failed();
                return;
            }

            _login_success();
        }

        private void odustani_Click(object sender, EventArgs e)
        {
            Success = false;
        }

        private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (Success)
            {
                return;
            }

            DialogResult result = MessageBox.Show("Da li zaista zelite izaci iz programa?", "Exit", MessageBoxButtons.YesNo);

            if (result == DialogResult.No)
            {
                e.Cancel = true;
            }
        }

        #endregion

        #region Login handlers

        void _login_success()
        {
            Success = true;
            LogiraniUposlenik = _loginHandler.LogiraniUposlenik;
            Close();
        }

        void _login_failed()
        {
            MessageBox.Show("Pogresna kombinacija username passworda.", "Greska", MessageBoxButtons.OK, MessageBoxIcon.None);
            Success = false;
        }

        #endregion

    }
}
